package com.eeepay.eeepay_v2.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.model.AgentAddInfo;
import com.eeepay.eeepay_v2.model.IntoPiecesInfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Ching on 2016/4/11.
 */
public class SPUtils {

    public static final String USER_INFO = "user_info";//用户信息

    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;
    private static Map<String, ?> maps = null;

    private static String FILE_NAME = "share_data";

    private static synchronized SharedPreferences getInstance() {
        if (sp == null) {
            sp = MyApplication.context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
            editor = sp.edit();
        }
        return sp;
    }

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param object
     */
    public static void put(String key, Object object) {

        getInstance();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, SerializeUtils.serialize(object));
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(String key, Object defaultObject) {
        getInstance();

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else {
            return SerializeUtils.deSerialization(sp.getString(key, "eeepay"));
        }
    }

    /**
     * @param key 移除历史记录
     */
    public static void removeHistory(String key) {

        sp = getInstance();

        if (editor != null) {
            editor.remove(key);
            SharedPreferencesCompat.apply(editor);
        }
    }

    /**
     * @param intoPieces 保存进件初始界面的数据
     */
    public static void saveIntoPieces(IntoPiecesInfo intoPieces) {

        sp = getInstance();
        String str;
//        try {
            str = SerializeUtils.serialize(intoPieces);
            if (editor != null) {
                editor.putString("IntoPiecesInfo", str);
                SharedPreferencesCompat.apply(editor);
            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public static IntoPiecesInfo getIntoPieces() {

        sp = getInstance();
        String str = null;

        if (editor != null) {
            str = sp.getString("IntoPiecesInfo", "eeepay");
        }

        IntoPiecesInfo intoPiecesInfo = (IntoPiecesInfo) SerializeUtils.deSerialization(str);
        return intoPiecesInfo;
    }


    /**
     * @param agentAddInfo  保存新增代理商的信息
     */
    public static void saveAgentAddInfo(AgentAddInfo agentAddInfo) {
        sp = getInstance();
        String str;
        str = SerializeUtils.serialize(agentAddInfo);
        if (editor != null) {
            editor.putString(Constant.KEY.AGENT_ADD_INFO, str);
            SharedPreferencesCompat.apply(editor);
        }
    }


    /**
     * @return 获取新增代理商的信息
     */
    public static AgentAddInfo getAgentAddInfo() {
        sp = getInstance();
        String str = null;

        if (editor != null) {
            str = sp.getString(Constant.KEY.AGENT_ADD_INFO, "eeepay");
        }

        AgentAddInfo agentAddInfo = (AgentAddInfo) SerializeUtils.deSerialization(str);
        return agentAddInfo;
    }

    /**
     * 保存string类型
     *
     * @param key
     * @param value
     */
    public static void saveString(String key, String value) {

        sp = getInstance();

        if (editor != null) {
            editor.putString(key, value);
            SharedPreferencesCompat.apply(editor);
        }
    }

    /**
     * 获得string类型
     *
     * @param key
     * @return
     */
    public static String getString(String key) {
        sp = getInstance();
        return sp.getString(key, "");
    }

//
//    /**
//     * @param rateList
//     * @return 保存服务费率
//     */
//    public static void saveRate(List<RateInfo> rateList) {
//        sp = getInstance();
//        editor.putInt("Rate_size", rateList.size());
//        for (int i = 0; i < rateList.size(); i++) {
//            editor.remove("Status_" + i);
//            editor.putString("Status_" + i, SerializeUtils.serialize(rateList.get(i)));
//        }
//        SharedPreferencesCompat.apply(editor);
//    }
//
//    /**
//     * @return 获取服务费率
//     */
//    public static List<RateInfo> getRate() {
//        sp = getInstance();
//        List<RateInfo> datas = new ArrayList<>();
//        int size = sp.getInt("Rate_size", 0);
//
//        for (int i = 0; i < size; i++) {
//            datas.add((RateInfo) SerializeUtils.deSerialization(sp.getString("Status_" + i, null)));
//        }
//        return datas;
//    }


    /**
     * @param datas 保存集合
     */
    public static void saveList(List datas, String key) {
        sp = getInstance();
        editor.remove(key + "_size");
        editor.putInt(key + "_size", datas.size());
        for (int i = 0; i < datas.size(); i++) {
            editor.remove(key + "_" + i);
            editor.putString(key + "_" + i, SerializeUtils.serialize(datas.get(i)));

        }
        SharedPreferencesCompat.apply(editor);
//        editor.commit();
    }

    /**
     * @param size
     * @param key  移除集合
     */
    public static void removeList(int size, String key) {
        sp = getInstance();
//        Log.d("saki", "removeList");
        for (int i = 0; i < size; i++) {
            editor.remove(key + "_" + i);
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * @param key
     * @return 获取集合
     */
    public static List getList(String key) {
        sp = getInstance();
        List datas = new ArrayList();
        int size = sp.getInt(key + "_size", 0);
        String str;
        for (int i = 0; i < size; i++) {
//            Log.d("saki", "getList: " + sp.getString(key + "_" + i, null));
            str = sp.getString(key + "_" + i, null);
            if (!TextUtils.isEmpty(str))
                datas.add(SerializeUtils.deSerialization(str));
        }
        return datas;
    }

    /**
     * SharedPreferences兼容类
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }
            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}
